<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Model\Data;
use Swoft\Apollo\Config;
use Swoft\Apollo\Exception\ApolloException;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;

use Swoft\Redis\Pool;
use App\Model\Dao\UserDao;

/**
 * Class UserData
 *
 * @since 2.0
 *
 * @Bean()
 */
class UserData
{
    /**
     * @Inject()
     *
     * @var UserDao
     */
    private $userDao;

    /**
     *
     * @Inject()
     *
     * @var Pool 默认连接使用的是 redis.pool
     */
    private $redis;

    public function getUserCountList(){
        $redisKey = 'userTop';
        $rs = $this->redis->ZREVRANGE($redisKey, 0, 10, 'WITHSCORES');
        if(!$rs){
            $rsDb = $this->userDao->getUserCountList();
            if($rsDb){
                $redisData = [];
                foreach($rsDb as $val){
                    $redisData[strval($val['userId'])] = intval($val['fans']);
                    array_push($rs, $val['userId']);
                }
                $this->redis->ZADD($redisKey, $redisData);
                $this->redis->EXPIRE($redisKey, 3600);
            }
        }
        return $rs;
    }

    public function getUserInfo(int $userId){
        $redisKey = 'userInfo:' . $userId;
        $rs = $this->redis->HGETALL($redisKey);
        if(!$rs){
            $rsDb = $this->userDao->getUserInfo($userId);
            if($rsDb){
                $redisData = [
                    'userId' => $rsDb['userId'],
                    'fans' => 0,
                    'orderCount' => 0,
                    'nickname' => $rsDb['nickname'],
                    'avatar' => $rsDb['avatar'],
                ];
                $rsCountDb = $this->userDao->getUserCount($userId);
                if($rsCountDb){
                    $redisData['fans'] = $rsCountDb['fans'];
                    $redisData['orderCount'] = $rsCountDb['orderCount'];
                }
                $this->redis->HMSET($redisKey, $redisData);
                $this->redis->EXPIRE($redisKey, 86400);
                $rs = $redisData;
            }
        }
        return $rs;
    }
}
